package jnpf.wx;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class MerSerialNoUtils {
	private static volatile int flowNoSix = 0;// 3位顺序号
    private static final String yyMMddHHmmssSSS = "yyMMddHHmmssSSS";
	/**
	 * 流水号规则 :32位流水
	 * 908（3位）+2位机器码+yyMMddHHmmssSSS（15位）+3位递增数+9位随机数
	 * @param
	 * @return
	 */
	public static synchronized String getFlowMchSeqNo() {
		StringBuffer flowNo = new StringBuffer();
		flowNo.append("908");
		flowNo.append(get2EndAddress());
		String date15 = get15Time();
		flowNo.append(date15);// 15位日期
		if (flowNoSix > 999) {
			flowNoSix = 0;
		}
		String flowNoFourStr = StringUtils.leftPad(flowNoSix + "", 3, "0");
		flowNo.append(flowNoFourStr);
		flowNoSix++;
		String aString = Integer.toString((int)((Math.random()*9+1)*100000000));//9位随机数
		flowNo.append(aString);
		return flowNo.toString();
	}
	
    /**
     * 按年后两位到毫秒
     * @return
     */
    public static String get15Time() {
        SimpleDateFormat format14 = format(yyMMddHHmmssSSS);
        return format14.format(new Date());
    }
    public static SimpleDateFormat format(String format) {
        return new SimpleDateFormat(format);
    }
	
	/**
	 * 拿到2位结尾地址
	 * 
	 * @return
	 */
	public static String get2EndAddress() {
		String ip = getAddress();
		String[] addr = ip.split("\\.");
		String address = addr[addr.length - 1];
		if (address.length() == 0) {
			return "00";
		} else if (address.length() == 1) {
			address = "0" + address;
		} else if (address.length() >=2){
			address =address.substring(0, 2);
		}
		return address;
	}
	
	public static String getAddress() {
		try {
			InetAddress ia = InetAddress.getLocalHost();
			return ia.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return "";
		}
	}
}
